/**
 * 这里主要是提供API请求服务
 */
import { apiHost } from './config';
import Nav from '../utils/navigate';

/**
 * 返回到页面的数据
 */
export interface HttpResponseToPage {
  code: number;
  items: any;
  message: string;
}

/**
 * 返回到服务的数据结构
 */
export interface HttpResposeToService {
  data: any | HttpResponseToPage;
  errMsg: string;
  statusCode: number;
}

/**
 * 略过token验证的请求地址
 */
const urls_ingore = [
  'session', 'createOrUpdateUserWxDetail',
  'login', 'register', 'getWeChatConfig'
];

/**
 * 判断当前请求的地址是否在略过token验证的请求地址里
 * @param key
 * @return boolean
 */
const is_in_array = (key: string) => {
  var testStr = ',' + urls_ingore.join(",") + ",";
  return testStr.indexOf("," + key + ",") != -1;
}

/**
 * 本地缓存token的key值
 */
const token_key = '_token';

/**
 * 获取token，如果没有token，且需要验证token，则调整登录页
 * @param url 
 */
const getToken = () => {
  let token = null;
  token = wx.getStorageSync(token_key);
  if (!token) {
    Nav.goToPanelDirect('/pages/index/index');
  }
  return token;
}

/**
 * 判断是否需要token
 * @param url 
 * @returns boolean
 */
const needToken = (url: string,) => {
  // return !is_in_array(url);
  console.log(!is_in_array(url));
  return false;
}

const doWithResponse = (res: HttpResposeToService) => {
  switch (res.statusCode) {
    // 没找到对应的请求地址
    case 404:
      Nav.goToPanelDirect('/pages/index/index');
      return null;
    // 没有登录
    case 401:
      Nav.goToPanelDirect('/pages/index/index');
      return null;
    // 服务器错误
    case 500:
      Nav.goToPanelDirect('/pages/index/index');
      return null;
  }
  return res.data;
}

// 创建请求头部信息
const makeHeader = (url: string, contentType: string) => {
  const _contentType = { 'content-type': contentType };
  if (!needToken(url)) {
    return _contentType;
  }
  const _authorization = { 'Authorization': `Bearer ${getToken()}`, };
  return { ..._contentType, ..._authorization };
}

export default {
  baseOptions(params: { url: string, data?: any, contentType?: string }, method: 'POST' | 'GET'): Promise<HttpResponseToPage> {
    let { url, data } = params
    let contentType = 'application/x-www-form-urlencoded'
    contentType = params.contentType || contentType;
    return new Promise((resolve, reject) => {
      wx.request({
        url: apiHost + url,
        dataType: 'json',
        header: makeHeader(url, contentType),
        method: method,
        data: data,
        success: function (res: HttpResposeToService) {
          const resp: HttpResponseToPage = doWithResponse(res);
          if (resp) {
            return resolve(resp);
          }
        },
        fail: function (e) {
          return reject(e)
        }
      })
    })
  },
  get(url: string, data: any): Promise<HttpResponseToPage> {
    let option = { url, data }
    return this.baseOptions(option, 'GET');
  },
  post(url: string, data: any, contentType: string = 'application/json'): Promise<HttpResponseToPage> {
    let params = { url, data, contentType }
    return this.baseOptions(params, 'POST')
  }
}